<template>
  <div class="can-container">
    <el-row>
      <el-col :span="5">
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="handleNewAdd"
            >新 增</el-button
          >
          <!-- <el-button class="btnuser">修 改</el-button> -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            :loading="deleteBatchBtnLoading"
            :disabled="!selectNodes.length"
            @click="handleBatchDelete"
            >删除所选</el-button
          >
        </div>
        <div id="eltree">
          <el-tree
            :data="data"
            show-checkbox
            :props="defaultProps"
            @node-click="handleNodeClick"
            @check="handleNodeCheck"
            ref="tree"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="18" :offset="1">
        <span class="title">组织机构信息</span>
        <div style="border-top:1px solid #C0C4CC;margin:35px 0px;"></div>
        <div class="form filter-container">
          <el-form
            :model="formData"
            label-width="110px"
            label-position="left"
            :rules="formDataRules"
            ref="formData"
          >
            <el-form-item label="组织机构名称" prop="name">
              <el-input
                v-model="formData.name"
                style="width:304px"
                placeholder="请输入"
                :readonly="editType == 1"
              ></el-input>
            </el-form-item>
            <el-form-item label="组织机构类型" prop="organizationTypeId">
              <el-select
                v-model="formData.organizationTypeId"
                style="width:304px"
                :disabled="editType == 1"
              >
                <el-option
                  v-for="item in organizationType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="组织机构区域"
              prop="regionId"
              v-show="editType == 0"
            >
              <el-cascader
                v-model="formData.regionId"
                style="width:304px"
                :show-all-levels="false"
                :props="defaultPropsDistrict"
                ref="organization"
              ></el-cascader>
            </el-form-item>
            <el-form-item
              label="组织机构区域"
              v-show="editType == 1"
              prop="regionName"
            >
              <el-input
                v-model="formData.regionName"
                :readonly="true"
                style="width:304px"
              ></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button
              type="primary"
              @click="handleSubmit('formData')"
              v-show="editType == 0"
              >确认</el-button
            >
            <el-button
              class="btnsearch btnReset"
              @click="handleReset()"
              v-show="editType == 0"
              >重置</el-button
            >
            <el-button
              type="danger"
              :loading="deleteBtnLoading"
              v-show="editType == 1"
              @click="handleDeleteOrganization"
              >删除</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getOrganizationData,
  getOrganizationType,
  getOrganizationDistrict,
  newAddOrganization,
  organizationBatchDelete
} from "@/api/project/system/organization.js";
export default {
  data() {
    var that = this;
    return {
      data: [],
      organizationType: [], //组织类型列表
      defaultProps: {
        label: "name"
      },
      defaultPropsDistrict: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node;
          getOrganizationDistrict({ parentId: value }).then(res => {
            const nodes = res.data.map(item => ({
              value: item.id,
              label: item.name,
              leaf: level >= 3
            }));
            resolve(nodes);
          });
        }
      },
      formData: {
        name: "",
        organizationTypeId: "",
        regionId: "",
        regionName: ""
      },
      formDataRules: {
        name: [{ required: true, message: "请填写", trigger: "blur" }],
        organizationTypeId: [
          { required: true, message: "请填写", trigger: "change" }
        ],
        regionId: [{ required: true, message: "请填写", trigger: "change" }]
      },
      organizationDistrict: [], //组织区域列表
      editType: 0, //0:新增，1:查看
      selectNodes: [], //树节点集合
      deleteBtnLoading: false,
      deleteBatchBtnLoading: false
    };
  },
  created() {
    this.handleInitData();
  },

  methods: {
    //初始化数据
    handleInitData: function() {
      this.getOrganizationData();
      this.getOrganizationType();
      this.getOrganizationDistrict(1);
    },
    //获取机构列表
    getOrganizationData: function() {
      let params = {
        page: 1,
        size: 999
      };
      getOrganizationData(params).then(res => {
        this.data = res.data.rows;
        this.selectNodes = [];
      });
    },
    //提交数据
    handleSubmit: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.formData));
          let lengthMax = formData["regionId"].length;
          delete formData["regionName"];
          formData["regionId"] = formData["regionId"][lengthMax - 1];
          formData["code"] = this.manageCode(this.formData.organizationTypeId);
          newAddOrganization(formData).then(res => {
            this.$message.success("操作成功！");
            this.getOrganizationData();
            this.handleReset("formData");
          });
        }
      });
    },
    //重置数据
    handleReset: function() {
      this.$refs["formData"].resetFields();
      this.formData = {
        name: "",
        organizationTypeId: "",
        regionId: ""
      };
    },
    //树结构点击回调
    handleNodeClick: function(data, node, nodeself) {
      this.editType = 1;
      this.handleReset();
      this.formData["name"] = data.name;
      this.formData["organizationTypeId"] = data.organizationTypeId;
      this.formData["regionName"] =
        data.city.name +
        "/" +
        data.district.name +
        "/" +
        data.town.name +
        "/" +
        data.village.name;
      this.formData["id"] = data.id;
    },
    //树结构勾选回调
    handleNodeCheck: function() {
      this.selectNodes = this.$refs["tree"].getCheckedNodes();
    },
    //新增组织结构
    handleNewAdd: function() {
      this.editType = 0;
      this.handleReset();
    },
    //删除机构
    handleDeleteOrganization: function() {
      this.$confirm("此操作将永久删除此组织, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(res => {
        this.deleteBtnLoading = true;
        let params = {
          ids: this.formData.id
        };
        organizationBatchDelete(params).then(res => {
          this.$message.success("操作成功！");
          this.getOrganizationData();
          this.handleNewAdd();
          this.deleteBtnLoading = false;
        });
      });
    },
    //批量删除组织结构
    handleBatchDelete: function() {
      this.$confirm("此操作将永久删除组织, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(res => {
        this.handleNewAdd();
        this.deleteBatchBtnLoading = true;
        let deleteIds = this.selectNodes
          .map(item => {
            return item.id;
          })
          .join(",");
        let params = {
          ids: deleteIds
        };
        organizationBatchDelete(params).then(res => {
          this.$message.success("操作成功！");
          this.getOrganizationData();
          this.deleteBatchBtnLoading = false;
        });
      });
    },
    //组织类型勾选回调
    handleSelectType: function(id) {
      this.getOrganizationDistrict(id);
    },
    //获取组织类型列表
    getOrganizationType: function() {
      getOrganizationType().then(res => {
        this.organizationType = res.data;
      });
    },
    //获取组织区域列表
    getOrganizationDistrict: function(id) {
      getOrganizationDistrict({ parentId: id }).then(res => {
        this.organizationDistrict = res.data;
      });
    },
    //返回Code
    manageCode: function(id) {
      return this.organizationType.filter(item => {
        return item.id == id;
      })[0].code;
    }
  }
};
</script>
<style lang="scss" scoped>
.can-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 154px);
  .title {
    font-size: 18px;
    font-weight: 500;
    color: rgba(72, 73, 77, 1);
    // line-height: 33px;
  }
}

.btnsearch {
  background: #969799;
  color: white;
}

.btnReset {
  background: white;
  color: #969799;
}
.btnuser {
  border: 1px solid #2e8ae6;
  color: #2e8ae6;
}
#eltree {
  margin: 20px 0px;
  height: 500px;
  overflow: auto;
}
#eltree /deep/ .el-icon-caret-right:before {
  content: "";
}
</style>
